import type { McpServer } from "@shared/triplit/types";

import { mcpServersQueries } from "../definitions/mcp-servers-queries";
import type { QueryConfig, QueryOneConfig, QueryResult } from "../types";
import { useStandardQuery, useStandardQueryOne } from "./use-standard-query";

/**
 * 获取所有 MCP servers 记录
 */
export function useMcpServers(
  config?: QueryConfig<"mcpServers">,
): QueryResult<McpServer[]> {
  return useStandardQuery(mcpServersQueries.all, config);
}

/**
 * 获取启用的 MCP servers
 */
export function useEnabledMcpServers(
  config?: QueryConfig<"mcpServers">,
): QueryResult<McpServer[]> {
  return useStandardQuery(mcpServersQueries.enabled, config);
}

/**
 * 获取按顺序排列的 MCP servers
 */
export function useOrderedMcpServers(
  config?: QueryConfig<"mcpServers">,
): QueryResult<McpServer[]> {
  return useStandardQuery(mcpServersQueries.ordered, config);
}

/**
 * 获取启用且按顺序排列的 MCP servers
 */
export function useEnabledOrderedMcpServers(
  config?: QueryConfig<"mcpServers">,
): QueryResult<McpServer[]> {
  return useStandardQuery(mcpServersQueries.enabledOrdered, config);
}

/**
 * 根据类型获取 MCP servers
 */
export function useMcpServersByType(
  type: "stdio" | "sse" | "streamableHTTP",
  config?: QueryConfig<"mcpServers">,
): QueryResult<McpServer[]> {
  return useStandardQuery(() => mcpServersQueries.byType(type), config);
}

/**
 * 获取启用的特定类型 MCP servers
 */
export function useEnabledMcpServersByType(
  type: "stdio" | "sse" | "streamableHTTP",
  config?: QueryConfig<"mcpServers">,
): QueryResult<McpServer[]> {
  return useStandardQuery(() => mcpServersQueries.enabledByType(type), config);
}

/**
 * 根据ID获取单个 MCP server
 */
export function useMcpServer(
  id: string,
  config?: QueryOneConfig<"mcpServers">,
): QueryResult<McpServer | null> {
  return useStandardQueryOne(
    () => {
      if (!id) {
        return mcpServersQueries.byId("__nonexistent__");
      }
      return mcpServersQueries.byId(id);
    },
    {
      ...config,
      enabled: !!id && config?.enabled !== false,
    },
  );
}

/**
 * 获取第一个可用的 MCP server
 */
export function useFirstMcpServer(config?: QueryConfig<"mcpServers">) {
  return useStandardQuery(mcpServersQueries.enabledOrdered, {
    ...config,
    select: (data) => data?.[0] || null,
  });
}

/**
 * 获取 stdio 类型的 MCP servers
 */
export function useStdioMcpServers(
  config?: QueryConfig<"mcpServers">,
): QueryResult<McpServer[]> {
  return useMcpServersByType("stdio", config);
}

/**
 * 获取 SSE 类型的 MCP servers
 */
export function useSseMcpServers(
  config?: QueryConfig<"mcpServers">,
): QueryResult<McpServer[]> {
  return useMcpServersByType("sse", config);
}

/**
 * 获取 HTTP 类型的 MCP servers
 */
export function useHttpMcpServers(
  config?: QueryConfig<"mcpServers">,
): QueryResult<McpServer[]> {
  return useMcpServersByType("streamableHTTP", config);
}
